package jsyf.oa.service.wreport;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.wreport.ModuleDao;
import jsyf.oa.entity.wreport.ModuleEntity;
import jsyf.oa.facade.wreport.ModuleFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lenovo on 2017/12/11.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class ModuleService implements ModuleFacade {
    @Autowired
    private ModuleDao dao;

    @Override
    public String save(String jsonData) {
        ModuleEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), ModuleEntity.class);
        if (StringUtils.isEmpty(entity.getId()) || "0".equals(entity.getId())) {
            dao.add(entity);
        } else {
            dao.update(entity);
        }
        return entity.getId();
    }

    @Override
    public Boolean removeById(String id) {
        return dao.removeById(id) > 0;
    }

    @Override
    public List<JSONObject> getTreeNodes() {
        List<JSONObject> nodeList = new ArrayList<>();

        JSONObject nodeRoot = new JSONObject();
        nodeRoot.put("id", "0");
        nodeRoot.put("pId", "-1");
        nodeRoot.put("name", "工作报告模块");
        nodeRoot.put("type", "root");
        nodeRoot.put("isParent", true);
        nodeRoot.put("open", true);
        nodeList.add(nodeRoot);

        List<JSONObject> list = dao.getJSONListByCondition("", new Object[]{});
        for (int i = 0; i < list.size(); i++) {
            JSONObject node = list.get(i);
            node.put("pId", "0");
            node.put("type", "module");
            nodeList.add(node);
        }

        return nodeList;
    }

    public List<JSONObject> getModuleENamesByUserId (String userId)
    {
        return dao.getModuleENamesByUserId(userId);
    }

    @Override
    public JSONObject getById(String id) {
        return dao.getJSONById(id);
    }
}
